

package com.starbaba.apiActivity.view;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.base.common.database.BaseDao;
import com.base.common.exception.AppException;
import com.base.common.log.LogService;
import com.opensymphony.xwork2.ModelDriven;
import com.starbaba.apiActivity.service.ApiActivityConfService;
import com.starbaba.core.utils.PropertyParamMapBuilder;
import com.starbaba.core.utils.Struts2Utils;
import com.starbaba.core.web.struts2.BaseAction;
import com.starbaba.model.dictionary.Constant;
import com.starbaba.system.user.model.UserVO;
import com.tuanzi.server.loan_base.model.db.apiModel.ApiActivity;
import com.tuanzi.server.loan_base.model.db.apiModel.ApiModelItem;
import com.tuanzi.server.loan_base.model.db.apiModel.ApiModelItemBasis;
import com.tuanzi.server.loan_base.model.db.apiModel.ApiModelItemOption;
import com.tuanzi.server.loan_base.model.db.apiModel.ApiModelItemOptionBasis;
import com.tuanzi.server.loan_base.model.db.apiModel.ApiModelValiRule;


/**
 * API模板从正式数据库复制到测试数据库
 * @author Administrator
 *
 */
@SuppressWarnings({"serial","unchecked","rawtypes","unused"})
public class ApiModelCopyToTestAction extends BaseAction implements ModelDriven<ApiModelItemOptionBasis> {

	@SuppressWarnings("deprecation")
    private static BaseDao testDao = new BaseDao("test_db");  // 测试数据库
	
	@SuppressWarnings("deprecation")
    private static BaseDao productDao = new BaseDao(Constant.POOL_LIFE);  // 正式数据库
	
	public static void main(String[] args) throws AppException {
		ApiModelCopyToTestAction action = new ApiModelCopyToTestAction();
		action.saveApiActivityToProd("33","魏壁烽");
	} 

	public void copyModelToProd() throws AppException{
		LogService.info("==============API模板复制，从正式复制到测试数据库=========start=========");
		HttpSession session = ServletActionContext.getRequest().getSession();
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		UserVO user = getUserVO();
		String userName = user.getUsername();
		
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String oldApiId = (String) paramsMap.get("apiId");
		saveApiActivityToProd(oldApiId,userName);
		
		LogService.info("==============API模板复制，从正式复制到测试数据库=========end=========");
	}
	
	private void saveApiActivityToProd(String oldApiId,String userName) throws AppException{
		LogService.info("----> oldApiId="+oldApiId+"  userName="+userName);
		ApiActivity newApiActivity = copyApiToProd(oldApiId,userName);
		copyItemToProd(newApiActivity,oldApiId);
	}
	
	
	private void copyItemToProd(ApiActivity newApiActivity,String oldApiId) throws AppException{
		SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		String currTime = dateFormater.format(date);
		
		String oldAllItemSql = "select * from loan_api_model_item i where i.api_id = ?";
		List<ApiModelItem> oldAllItemList = productDao.list(oldAllItemSql, ApiModelItem.class, oldApiId);
		setParentItem(oldAllItemList,newApiActivity);
		
		Long newApiId = newApiActivity.getId();
		for(ApiModelItem oldItem:oldAllItemList){
			ApiModelItem newItem = saveItemToProd(oldItem,newApiId); //保存新Item
		}
		
	}
	
	//对带有指定父项的item先进行另外保存，获得旧itemId和新的itemId的映射
	public void setParentItem(List<ApiModelItem> oldAllItemList,ApiActivity newApiActivity) throws AppException{
		LogService.info("----设置父级item----start----------------->");
		Long newApiId = newApiActivity.getId();
		Map<Long,Long> map = new HashMap<Long, Long>();  //存储旧父itemId和新父itemId的映射关系
		int count = oldAllItemList.size();
		for(int i=0;i<count;i++){
			ApiModelItem item = oldAllItemList.get(i);
			Integer haveParent = item.getHave_parent();
			if(haveParent == 1){
				Long oldParentItemId = item.getParent_item_id();  
				Long newParentItemId = null;  //新的父itemId
				if(map.containsKey(oldParentItemId)){
					newParentItemId = map.get(oldParentItemId);
				}else{
					newParentItemId = saveParentItem(oldParentItemId,oldAllItemList,newApiId);
					map.put(oldParentItemId, newParentItemId);
					i--;
					count--;
					LogService.info("----> 老的父级Item: "+oldParentItemId+"  新的父级Item: "+newParentItemId);
				}
				item.setParent_item_id(newParentItemId);
			}
		}
		LogService.info("----设置父级item----end----------------->");
	}
	
	//先保存父item
	public Long saveParentItem(Long oldParentItemId,List<ApiModelItem> oldItemList,Long newApiId) throws AppException{
		Long newItemId = 0l;
		for(ApiModelItem oldItem:oldItemList){
			Long itemId = oldItem.getId();
			if(itemId.longValue() == oldParentItemId){
				ApiModelItem parentItem = saveItemToProd(oldItem,newApiId); //保存父Item
				newItemId = parentItem.getId();
				oldItemList.remove(oldItem); //保存后删除对应的元素
				break;
			}
		}
		return newItemId;
	}
	
	//通过apiId复制，返回新复制的Api主键
	private ApiActivity copyApiToProd(String apiId,String username) throws AppException{
		SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		String currTime = dateFormater.format(date);
		
		String selectSql = "Select * From loan_api_activity api where api.id = ?";
		ApiActivity api = productDao.get(selectSql, ApiActivity.class, apiId);
		api.setId(null);
		api.setUser_name(username);
		api.setCtime(currTime);
		api.setUptime(currTime);
		Long prodApiId = testDao.addReturnGeneratedKey(api);
		api.setId(prodApiId);
		
		LogService.info("----> prodApiId="+prodApiId);
		return api;
	}
	
	// 保存item到正式数据库
	private ApiModelItem saveItemToProd(ApiModelItem oldItem,Long newApiId) throws AppException{
		SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		String currTime = dateFormater.format(date);
		
		Long oldItemBasisId = oldItem.getItem_basis_id();
		Long oldItemId = oldItem.getId();
		ApiModelItem newItem = oldItem;
		
		// 查询测试数据库的itembasis
		String oldItemBasisSql = "select * from loan_api_model_itembasis ib where ib.id = ?";
		ApiModelItemBasis oldItemBasis = productDao.get(oldItemBasisSql, ApiModelItemBasis.class, oldItemBasisId);
		String dataKey = oldItemBasis.getData_key(); 
		
		String newItemBasisSql = "select * from loan_api_model_itembasis ib where ib.data_key = ?";
		ApiModelItemBasis newItemBasis = testDao.get(newItemBasisSql, ApiModelItemBasis.class, dataKey);
		if(newItemBasis == null){  // 正式数据没有对应的item_basis,先保存
			oldItemBasis.setId(null);
			oldItemBasis.setCreate_time(currTime);
			oldItemBasis.setUpdate_time(currTime);
			Long newItemBasisId = testDao.addReturnGeneratedKey(oldItemBasis);
			oldItemBasis.setId(newItemBasisId);
			newItemBasis = oldItemBasis;
		}
		newItem.setApi_id(newApiId);
		newItem.setItem_basis_id(newItemBasis.getId());
		
		// 保存正式数据的item
		newItem.setId(null);
		Long newItemId = testDao.addReturnGeneratedKey(newItem);
		newItem.setId(newItemId);
		LogService.info("----> 新的ItemId="+newItemId+"  老的ItemId="+oldItemId);
		
		// 保存正式数据库的itemOption
		saveItemOptionToProd(oldItemId,newItem);
		
		// 保存正式数据库的valiRule
		saveItemValiRuleToProd(oldItemId,newItem);
		
		return newItem;
	}
	
	// 保存item的校验规则到正式数据库
	private void saveItemValiRuleToProd(Long oldItemId,ApiModelItem newItem) throws AppException{
		Long newItemId = newItem.getId();
		
		String selectSql = "select * from loan_api_model_vali_rule vr where item_id = ? ";
		List<ApiModelValiRule> oldValiRuleList = productDao.list(selectSql, ApiModelValiRule.class, oldItemId);
		if(oldValiRuleList == null || oldValiRuleList.size() == 0){
			return;
		}
		for(ApiModelValiRule oldRule :oldValiRuleList){
			oldRule.setId(null);
			oldRule.setItem_id(newItemId);
			testDao.add(oldRule);
		}
	}
	
	// 保存item的option
	private void saveItemOptionToProd(Long oldItemId,ApiModelItem newItem) throws AppException{
		Long newItemId = newItem.getId();
		
		String selectSql = "select * from loan_api_model_item_option where item_id = ? order by sort";
		List<ApiModelItemOption> oldOptionList = productDao.list(selectSql, ApiModelItemOption.class, oldItemId);
		if(oldOptionList == null || oldOptionList.size() == 0){
			return;
		}
		for(ApiModelItemOption oldOption : oldOptionList){
			ApiModelItemOptionBasis newBasisOption = checkOrSaveBasisOptionOfProd(oldOption,newItem);  // 检查是否保存基础的option
			oldOption.setId(null);
			oldOption.setItem_id(newItemId);
			oldOption.setOption_basis_id(newBasisOption.getId());
			testDao.add(oldOption);
		}
	}
	
	// 检查正式的basis_option是否已经存在,不存在保存
	private ApiModelItemOptionBasis checkOrSaveBasisOptionOfProd(ApiModelItemOption oldOption,ApiModelItem newItem) throws AppException{
		SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		String currTime = dateFormater.format(date);
		
		Long newItemBasisId = newItem.getItem_basis_id();
		Long oldBasisOptionId = oldOption.getOption_basis_id();
		ApiModelItemOption newOption = oldOption;
		
		String oldBasisOptionSql = "SELECT * FROM loan_api_model_item_optionbasis op where op.id = ?";
		ApiModelItemOptionBasis oldBasisOption = productDao.get(oldBasisOptionSql, ApiModelItemOptionBasis.class, oldBasisOptionId);
		String optionKey = oldBasisOption.getOption_key();
		
		String newBasisOptionSql = "SELECT * FROM loan_api_model_item_optionbasis op where op.itembasis_id = ? and op.option_key = ?";
		ApiModelItemOptionBasis newBasisOption = testDao.get(newBasisOptionSql, ApiModelItemOptionBasis.class, newItemBasisId,optionKey);
		if(newBasisOption == null){  // 正式数据不存在basis_option
			newBasisOption = oldBasisOption;
			newBasisOption.setId(null);
			newBasisOption.setItembasis_id(newItemBasisId);
			newBasisOption.setCreate_time(currTime);
			newBasisOption.setUpdate_time(currTime);
			Long newBasisOptionId = testDao.addReturnGeneratedKey(oldBasisOption);
			newBasisOption.setId(newBasisOptionId);
			LogService.info("----> 测试数据库不存在basisItem：newItemBasisId="+newItemBasisId+"  optionKey="+optionKey);
		}
		return newBasisOption;
	}
	
	@Override
	public ApiModelItemOptionBasis getModel() {
		
		return null;
	}

}
















